/**
 * Created by Administrator on 2015/8/28.
 *
 * code状态码: 0.首次进入登录界面或注销成功;1注册成功;2.注册失败;3.用户名或密码错误;4.权限不正确，您不是管理员
 * */
var express = require('express');
var router = express.Router();
var loginAndRegisterService = require('../src/service/loginAndRegisterService');

var adminService = require('../src/service/adminService');

/**跳转至登录界面*/
router.get('/toLogin', function (req, res, next) {
    var code,localUsername;
    code=(req.param('code') == undefined)?0:req.param('code');
    localUsername=(res.cookie['localUsername']!=undefined)?res.cookie['localUsername']:'';
    req.session.currentUser = undefined;

    res.render('EJS/login', {code: code,localUsername:localUsername});
});

/**验证用户登录信息*/
router.post('/login', function (req, res, next) {
    loginAndRegisterService.login(req, res, function (result) {
        var user = result;
        if (user != undefined) {
            if (user.level == 1) {
                res.redirect('/admin/activityManage/activityList?page=1');
            } else if (user.level == 2) {
                res.redirect('/admin/activityManage/activityList?page=1');
            } else if (user.level == 3) {
                res.redirect('/customer/active/activityList?page=1');
            }
        } else {
            res.render('EJS/login', {code: 3,localUsername:req.param('username')});
        }
    });
});
/**跳转到注册页面*/
router.get('/toRegister', function (req, res, next) {
    res.render('EJS/register', {title: 'Express'});
});
/**检验用户名是否已经被使用*/
router.post('/checkUsername', function (req, res, next) {
    loginAndRegisterService.checkUsername(req, res, function (result) {
        res.send(result);
    })
});
/**注册*/
router.post('/register', function (req, res, next) {
    loginAndRegisterService.register(req, res, function (result) {
        res.send(result);
    })
});
//首页
router.get('/', function (req, res, next) {
    loginAndRegisterService.firstPages(req, res, function (result) {
        res.render('EJS/firstPage', {subject: result});
    })
});
router.post('/getUserName', function (req, res, next) {
    res.send(req.session.currentUser.name);
});

module.exports = router;